import { reactive } from 'vue'
import http from '../../utils/http'

export default {
  state: reactive({
    todoList: []
  }),
  actions: {
    /**
     * 获取所有事项
     */
    async getTodoList ({ state }) {
      state.todoList = await http.get('todo/getList')
    },
    /**
     * 更改事项
     * @param {*} todoItem 
     */
    async modifyTodo ({ state, dispatch }, todoItem) {
      await http.put('todo', { data: todoItem })
      dispatch('getTodoList')
    },
    /**
     * 添加事项
     * @param {*} todoItem 
     */
    async addTodo ({ state, dispatch }, todoItem) {
      await http.post('todo', { data: todoItem })
      dispatch('getTodoList')
    },
    /**
     * 将事项状态设置为未完成
     * @param {*} _id 
     */
    undoTodo ({ state }, _id) {
      state.todoList.some(async i => {
        if (i._id !== _id) return
        i.status = 0
        await http.put('todo', { data: i })
        return true
      })
    },
    /**
     * 将事项状态设置为已完成
     * @param {*} _id 
     */
    doneTodo ({ state }, _id) {
      state.todoList.some(async i => {
        if (i._id !== _id) return
        i.status = 1
        await http.put('todo', { data: i })
        return true
      })
    },
    /**
     * 删除指定事项
     * @param {*} _id 
     */
    async delTodo ({ state, dispatch }, _id) {
      await http.delete('todo', { data: { _id } })
      dispatch('getTodoList')
    }
  }
}
